<template>
  <div class="article-list">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" :success-text="refreshSucssessText"
      :success-duration="1500">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :error.sync="error"
        error-text="请求失败，点击重新加载">
        <article-item v-for="(item, index) in list" :key="index" :title="item.title" :article="item"></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article.js'
import ArticleItem from '@/components/article-item'
// const arr = '1,2,3,4,5,6,7,8,9'
// console.log(arr.slice(0, arr.lastIndexOf(',')) + arr.substr(arr.lastIndexOf(',') + 1))

export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: {
    // 当前频道列表的id和name
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [], // 存储列表数据的数组
      loading: false, // 列表加载loading状态
      finished: false, // 加载结束状态
      timestamp: Date.now(), // 请求获取下页数据的时间戳
      error: false, // 加载失败提示状态
      isLoading: false, // 下拉刷新的loading状态
      refreshSucssessText: '刷新成功'// 下拉刷新成功提示文本
    }
  },
  created () {

  },
  methods: {
    // 初始化或滚动到底部的时候会触发调用 onLoad
    async onLoad () {
      try {
        // 请求文章列表数据
        const res = await getArticles({
          channel_id: this.channel.id, // 频道ID
          timestamp: this.timestamp, // 当前时间戳
          with_top: 1 // 是否包含置顶
        })
        console.log(res)
        // 模拟随机失败
        // if (Math.random() > 0.5) {
        //   JSON.parse('sdfsdf')
        // }
        const { results } = res.data.data
        this.list.push(...results)
        this.timestamp = res.data.data.pre_timestamp
        this.loading = false
        if (!results.length) {
          this.finished = true
        }
      } catch (err) {
        console.log(err)
        this.error = true
        this.loading = false
      }
    },
    async onRefresh () {
      try {
        // 请求文章列表数据
        const res = await getArticles({
          channel_id: this.channel.id, // 频道ID
          timestamp: Date.now(), // 当前时间戳
          with_top: 0 // 是否包含置顶
        })
        // 模拟随机失败
        // if (Math.random() > 0.5) {
        //   JSON.parse('sdfsdf')
        // }
        const { results } = res.data.data
        this.list.unshift(...results)
        this.isLoading = false
        this.refreshSucssessText = `刷新成功,更新了${results.length}条数据`
      } catch (err) {
        this.isLoading = false
        this.refreshSucssessText = '刷新失败'
      }
    }
  }
}
</script>

<style scoped lang='less'>
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>
